using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows;
using AdRotatorXNA;
using Microsoft.Phone.Shell;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace StarTrooper2DGame
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        #region Fields

        public GraphicsDeviceManager Graphics { get; private set; }
        public SpriteBatch SpriteBatch { get; private set; }

        ScreenManager screenManager;

        public static GameState state = new GameState();

        List<String> ScreenStateList = new List<String>();

        public static bool ExitGame;

        #endregion

        #region initialise
        public Game1()
        {
            Application.Current.UnhandledException += new EventHandler<ApplicationUnhandledExceptionEventArgs>(Current_UnhandledException);

            // Extend battery life under lock.
            InactiveSleepTime = TimeSpan.FromSeconds(1);

            Content.RootDirectory = "Content";

            Graphics = new GraphicsDeviceManager(this);
            Graphics.IsFullScreen = true;
            Graphics.SupportedOrientations = DisplayOrientation.Portrait;

            // Frame rate is 30 fps by default for Windows Phone.
            TargetElapsedTime = TimeSpan.FromTicks(333333);

            // you can choose whether you want a landscape or portait
            // game by using one of the two helper functions.
            InitializePortraitGraphics();
            // InitializeLandscapeGraphics();

            // Create the screen manager component.
            screenManager = new ScreenManager(this);

            Components.Add(screenManager);

            PhoneApplicationService.Current.Activated += PhoneApplicationService_Activated;
        }


        protected override void OnActivated(object sender, EventArgs args)
        {
            try
            {
                LittleWatson.CheckForPreviousException("starter3dseries@xna-uk.net", "Starter2D XNA Example Error Report");
            }
            catch { }
            base.OnActivated(sender, args);
        }

        void Current_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            if (System.Diagnostics.Debugger.IsAttached)
            {
                // An unhandled exception has occurred; break into the debugger
                System.Diagnostics.Debugger.Break();
            }
            else
            {
                try
                {
                    LittleWatson.ReportException((Exception)e.ExceptionObject, "Starter2D XNA Error");
                }
                catch { }
            }
        }

        /// <summary>
        /// Helper method to the initialize the game to be a portrait game.
        /// </summary>
        private void InitializePortraitGraphics()
        {
            Graphics.PreferredBackBufferWidth = 480;
            Graphics.PreferredBackBufferHeight = 800;
        }

        /// <summary>
        /// Helper method to initialize the game to be a landscape game.
        /// </summary>
        private void InitializeLandscapeGraphics()
        {
            Graphics.PreferredBackBufferWidth = 800;
            Graphics.PreferredBackBufferHeight = 480;
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here

            //initialise the AdRotator Component
            AdRotatorXNAComponent.Initialize(this);

            //Specify where you want the Ad to start displaying (based on the top left corner of the Ad)
            //Note if screens alter this value be sure to set it to the correct position for every screen
            AdRotatorXNAComponent.Current.AdPosition = new Vector2(0, GraphicsDevice.Viewport.Height - 80);

            //Optionally specify your own House Ad which will display if there is no network
            AdRotatorXNAComponent.Current.DefaultHouseAdImage = Content.Load<Texture2D>(@"AdRotator\AdRotatorDefaultAdImage");

            //Event handler to do something should the user click on your Default House Ad
            AdRotatorXNAComponent.Current.DefaultHouseAdClick += new AdRotatorXNAComponent.DefaultHouseAdClickEventHandler(Current_DefaultHouseAdClick);

            //Optionally specify the slide (popup) direction for the Ad
            AdRotatorXNAComponent.Current.SlidingAdDirection = SlideDirection.Right;

            //Optionally Set the local configuration file used to set the default Ad Locations
            AdRotatorXNAComponent.Current.DefaultSettingsFileUri = "defaultAdSettings.xml";

            //Optionally set a URL from where to pull the configuration file down remotely each time the game is run
            AdRotatorXNAComponent.Current.SettingsUrl = "http://xna-uk.net/adrotator/XNAdefaultAdSettingsV2.xml";

            //Add the control to the XNA Component list which will display the ad
            //Note as this is XNA be sure to just to this for the game states you want it shown.
            Components.Add(AdRotatorXNAComponent.Current);

            AppStart();

            base.Initialize();
        }

        void Current_DefaultHouseAdClick()
        {
            try
            {
                MessageBox.Show("You clicked on my Ad, thanks very much");
            }
            catch { }
        }

        #endregion

        #region Content

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {

        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        #endregion


        #region Update
        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            //If the users wishes to exit, do so
            if (ExitGame) this.Exit();

            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed && screenManager.CurrentScreenName() == "MainMenuScreen")
                //Are you sure?
                screenManager.AddScreen(new MessageBoxScreen("Are you sure you want to Exit?"), PlayerIndex.One);

            base.Update(gameTime);
        }

        #endregion

        #region Draw
        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here

            base.Draw(gameTime);
        }

        #endregion

        #region Tombstoning

        private void PhoneApplicationService_Activated(object sender, ActivatedEventArgs e)
        {
            // execute any logic required after activation
            if (!e.IsApplicationInstancePreserved)
            {
                GameActivated();
            }
        }

        private void GameActivated()
        {
            if (PhoneApplicationService.Current.State.ContainsKey("MenuState"))
            {
                ScreenStateList = PhoneApplicationService.Current.State["MenuState"] as List<String>;
                foreach (String screenstate in ScreenStateList)
                {
                    Type screenType = Type.GetType(screenstate);
                    GameScreen screen = Activator.CreateInstance(screenType) as GameScreen;
                    screenManager.AddScreen(screen, PlayerIndex.One);
                    Debug.WriteLine("XNA Screen {0}", screenstate);

                }
                PhoneApplicationService.Current.State.Remove("MenuState");
                Debug.WriteLine("XNA Screenstates Loaded");

                //Get Game Save State Here
                if (PhoneApplicationService.Current.State.ContainsKey("GameSaveState"))
                {
                    state = PhoneApplicationService.Current.State["GameSaveState"] as GameState;
                    PhoneApplicationService.Current.State.Remove("GameSaveState");

                }
            }
            else
            {
                AppStart();
            }
        }

        private void AppStart()
        {
                GameScreen[] StartScreens = new GameScreen[2];
                StartScreens[0] = new BackgroundScreen();
                StartScreens[1] = new MainMenuScreen();
                Texture2D LoadingTexture = Content.Load<Texture2D>(@"MenuAssets\SplashScreenImage");
                LoadingScreen.Load(screenManager, 2, LoadingTexture, PlayerIndex.One, StartScreens);
        }

        protected override void OnDeactivated(object sender, EventArgs args)
        {
            if (screenManager.CurrentScreenName() == "StarTrooper2DGameplayScreen")
            {
                screenManager.AddScreen(new PauseGameScreen(), PlayerIndex.One);
               
            }

            foreach (GameScreen screen in screenManager.GetScreens())
            {
                if (screen.IsSerializable)
                {
                    ScreenStateList.Add(screen.GetType().AssemblyQualifiedName);

                }
            }
            if (PhoneApplicationService.Current.State.ContainsKey("MenuState"))
            {
                PhoneApplicationService.Current.State.Remove("MenuState");
            }
            PhoneApplicationService.Current.State.Add("MenuState", ScreenStateList);
            //Save Game save state Here
            if (PhoneApplicationService.Current.State.ContainsKey("GameSaveState"))
            {
                PhoneApplicationService.Current.State.Remove("GameSaveState");
            }
            PhoneApplicationService.Current.State.Add("GameSaveState", state);

            base.OnDeactivated(sender, args);
        }

        protected override void OnExiting(object sender, System.EventArgs args)
        {

            base.OnExiting(sender, args);
        }
        #endregion

    }
}
